package com.qunar.wan;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * User: cyoung Date: 11/07/13 Time: 3:27 PM
 */
public final class AppConfig {
    private AppConfig() { }

    private static ResourceBundle rb = null;
    private static final Locale locale = new Locale("zh", "CN");
    private static Logger logger = LoggerFactory.getLogger(AppConfig.class);

    static {
        try {
            rb = ResourceBundle.getBundle("appConfig", locale);
        } catch (Exception e) {
            logger.error("error", e);
        }
    }

    public static String getItem(final String item, final String defaultValue) {
        String value = null;
        if (rb != null) {
            try {
                value = rb.getString(item.trim());
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        if (value == null) {
            return defaultValue;
        }
        return value.trim();
    }

    public static String getItem(final String item, final String defaultValue, final String charset) {
        try {
            return new String(getItem(item, defaultValue).getBytes("ISO-8859-1"), charset);
        } catch (UnsupportedEncodingException e) {
            logger.error("getIteam error");
        }
        return defaultValue;
    }

    public static int getIntItem(final String item, final String defaultValue) {
        int i = 0;
        String value = getItem(item, defaultValue);
        try {
            i = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            logger.error("item=" + item + ", defaultValue=" + defaultValue, e);
        }
        return i;
    }

    public static boolean getBooleanItem(final String item, final boolean defaultValue) {
        boolean b = false;
        String value = getItem(item, Boolean.valueOf(defaultValue).toString());
        if (value != null && value.equalsIgnoreCase("true")) {
            b = true;
        }
        return b;
    }
}
